<template>
  <div class="mainMoudle">
        <div id="lefttd">
          <h3>整合测区名</h3>
          <el-input v-model="zhcqm" size="mini" style="width:200px"></el-input>
          <h3>1万标准图</h3>
          <el-input v-model="ywbzt" size="mini" style="width:200px"></el-input>
          <h3>绘制方式</h3>
          <el-button class="action-button esri-icon-polygon" size="mini" type="primary" id="polygonButton"></el-button>
          <el-button class="action-button esri-icon-checkbox-unchecked" size="mini" type="primary" id="rectangleButton"></el-button>
          <el-button class="action-button esri-icon-radio-unchecked" size="mini" type="primary" id="circleButton"></el-button>
          <el-button class="action-button esri-icon-trash" size="mini" type="primary" id="resetBtn"></el-button>
          <h3>提取方式</h3>
          <el-radio-group v-model="tqfs" size="mini">
            <el-radio-button label="相交"></el-radio-button>
            <el-radio-button label="包含"></el-radio-button>
          </el-radio-group>
          <div class="btnGroup">
          <el-button size="mini" icon="el-icon-search" id="secarch"></el-button>
          <el-button size="mini" icon="el-icon-delete"></el-button>
          <el-button size="mini" icon="el-icon-download" id="testbt"></el-button>
          </div>
        </div>
        <div id="righttd">

          1212
        </div>
  </div>
</template>
<style scoped>
  @import url('https://js.arcgis.com/4.7/esri/css/main.css');
  .mainMoudle{
    width:100%;height:100%;position: relative;
  }
  #lefttd{
    box-sizing: border-box;
    border-right: #a1a1a1 solid 1px;
    padding: 0 10px;
    width: 260px;
    height:100%;
    vertical-align: top;
  }
  #righttd{
    position: absolute;right: 0;left: 260px;z-index: 10000;top: 0;bottom: 0;
  }
  #lefttd h3{
    padding: 0 0 0 15px;
    margin: 0;
    line-height: 40px;
    font-size: 14px;
    position: relative;
  }
  #lefttd .el-input--mini{
    width:100%!important;
  }
  #lefttd .el-button--primary{
    background-color: #4d6390;
    border-color: #4d6390;
  }
  #lefttd .el-radio-group .el-radio-button__orig-radio:checked + .el-radio-button__inner{
    background-color: #4d6390!important;
    border-color: #4d6390!important;
  }
  #lefttd h3:after{
    content: "";
    width: 3px;
    height: 3px;
    background-color: #000;
    position: absolute;
    top: 19px;
    left: 5px;
    z-index: 10001;
  }
</style>
<script>
 
  // js 代码
  //import  arcgisConfig  from '@/views/map/mapConfig'
  import esriLoader from 'esri-loader';
  //
  export default {
 
    data () {
      return {
        zhcqm: '',
        ywbzt:'',
        tqfs:'相交',
        data:[],
        alldata:[],
        totalCount:1,
        pszie:8,
        nowpagr:1,
        dialogVisible:false,
        selmode:'all',
        input:''
      }
    },
    created: function () {
      
    },
    mounted: function () {
      const _this = this;
      this.$nextTick(function () {
           _this.test1();
      })
    },
    methods:{
      cleardata(){
        this.data = []
        this.alldata = []
      },
      handleSizeChange(val) {
        this.pszie = val
        this.setdata();
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.nowpagr = val
        this.setdata();
        console.log(`当前页: ${val}`);
      },
      setdata(){
        //this.data = [];
        this.data = this.alldata.slice(this.pszie*(this.nowpagr-1),this.pszie*(this.nowpagr-1)+this.pszie);
      },
      download(){
        switch(this.selmode){
          case 'all':{
            this.$message('全部下载');
          }break;
          case 'some':{
            this.$message('部分下载:'+this.input);
          }break;
        }
        dialogVisible=false;
      },
      test1:function () {
        let _this = this;
        const options = {
           url: "https://js.arcgis.com/4.7" //本地js资源
        };
        esriLoader.loadModules ([
          "esri/Map",
          "esri/views/MapView",

          "esri/layers/TileLayer",
          "esri/Basemap",

          "esri/widgets/Sketch/SketchViewModel",
          "esri/Graphic",
          "esri/layers/GraphicsLayer",          
          
          "esri/tasks/QueryTask",
          "esri/tasks/support/Query",

          "esri/core/Collection",

          "dojo/dom",
          "dojo/on",
          "dojo/domReady!"
        ],options)
          .then (([
                    Map, MapView,
                    TileLayer,Basemap,
                    SketchViewModel, Graphic, GraphicsLayer,
                    QueryTask, Query,
                    Collection,
                    dom, on
                  ]) => 
          {
            var veclayer = new TileLayer({
                url: "http://www.dzmap.cn/arcgis/rest/services/vec/MapServer",
                title: "矢量地图",
            });
            var cvalayer = new TileLayer({
                url: "http://www.dzmap.cn/arcgis/rest/services/ant/MapServer",
                title: "矢量注记地图",
            });
            var cialayer = new TileLayer({
                url: "http://www.dzmap.cn/arcgis/rest/services/imgzhuji/MapServer",
                title: "影像注记地图",
            });
            var imglayer = new TileLayer({
                url: "http://www.dzmap.cn/arcgis/rest/services/img_services/MapServer",
                title: "影像地图",
            });

            var vecBasemap = new Basemap({
              baseLayers: [
              veclayer
              ],
              id:"sldt",
              title: "矢量地图",
              thumbnailUrl: "http://www.dzmap.cn/arcgis/rest/services/vec/MapServer/export?bbox=108.51210030209486%2C24.364923864731523%2C114.52924109256693%2C30.40363488070311&bboxSR=&layers=&layerDefs=&size=&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&dynamicLayers=&gdbVersion=&mapScale=&f=image",
            });

            var imgBasemap = new Basemap({
              baseLayers: [
              imglayer
              ],
              id:"xyt",
              title: "影像地图",
              thumbnailUrl: "http://www.dzmap.cn/arcgis/rest/services/img_services/MapServer/export?bbox=108.51210030209486%2C24.364923864731523%2C114.52924109256693%2C30.40363488070311&bboxSR=&layers=&layerDefs=&size=&imageSR=&format=png&transparent=false&dpi=&time=&layerTimeOptions=&dynamicLayers=&gdbVersion=&mapScale=&f=image",
            });


            var map = new Map({
              basemap: vecBasemap,
              //layers: [cialayer, veclayer, cvalayer],
              center: [113, 29],
              zoom: 2,
            });

            var view = new MapView({
              container: "viewDiv",
              map: map
            });

            /********************
             * Add feature layer
             ********************/

            // Carbon storage of trees in Warren Wilson College.
            // var featureLayer = new FeatureLayer({
            //   url: "http://www.dzmap.cn/arcgis/rest/services/hn1w/MapServer/0"
            // });

            //map.add(featureLayer);

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            var tempGraphicsLayer = new GraphicsLayer();
            var updateGraphic;

            map.add(tempGraphicsLayer);

            var pointSymbol = { // symbol used for points
              type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
              style: "square",
              color: "#8A2BE2",
              size: "16px",
              outline: { // autocasts as new SimpleLineSymbol()
                color: [255, 255, 255],
                width: 3 // points
              }
            }
            var polylineSymbol = { // symbol used for polylines
              type: "simple-line", // autocasts as new SimpleMarkerSymbol()
              color: "#8A2BE2",
              width: "3",
              style: "solid"
            }

            var polygonSymbol = { // symbol used for polygons
              type: "simple-fill", // autocasts as new SimpleMarkerSymbol()
              color: "rgba(138,43,226, 0.8)",
              style: "solid",
              outline: {
                color: "white",
                width: 1
              }
            }

            view.when(function() {
              // create a new sketch view model
              var sketchViewModel = new SketchViewModel({
                view: view,
                layer: tempGraphicsLayer,
                pointSymbol: pointSymbol,
                polylineSymbol: polylineSymbol,
                polygonSymbol: polygonSymbol
              });

              setUpClickHandler();
              // ************************************************************
              // Get the completed graphic from the event and add it to view.
              // This event fires when user presses
              //  * "C" key to finish sketching point, polygon or polyline.
              //  * Double-clicks to finish sketching polyline or polygon.
              //  * Clicks to finish sketching a point geometry.
              // ***********************************************************
              sketchViewModel.on("draw-complete", addGraphic);
              sketchViewModel.on("update-complete", addGraphic);
              sketchViewModel.on("update-cancel", addGraphic);

              function addGraphic(evt) {
                var geometry = evt.geometry;
                var symbol;

                // Choose a valid symbol based on return geometry
                switch (geometry.type) {
                  case "point":
                    symbol = pointSymbol;
                    break;
                  case "polyline":
                    symbol = polylineSymbol;
                    break;
                  default:
                    symbol = polygonSymbol;
                    break;
                }
                // Create a new graphic; add it to the GraphicsLayer
                var graphic = new Graphic({
                  geometry: geometry,
                  symbol: symbol
                });
                tempGraphicsLayer.add(graphic);
                // Remove stored reference to the updated graphic
                // Required in 'update-complete' callback specifically
                updateGraphic = null;
              }

              // *************************************
              // activate the sketch to create a point
              // *************************************
              var drawPointButton = document.getElementById("pointButton");
              drawPointButton.onclick = function() {
                reset();
                // set the sketch to create a point geometry
                sketchViewModel.create("point");
                setActiveButton(this);
              };

              // ****************************************
              // activate the sketch to create a polyline
              // ****************************************
              var drawLineButton = document.getElementById("polylineButton");
              drawLineButton.onclick = function() {
                reset();
                // set the sketch to create a polyline geometry
                sketchViewModel.create("polyline");
                setActiveButton(this);
              };

              // ***************************************
              // activate the sketch to create a polygon
              // ***************************************
              var drawPolygonButton = document.getElementById("polygonButton");
              drawPolygonButton.onclick = function() {
                reset();
                // set the sketch to create a polygon geometry
                sketchViewModel.create("polygon");
                setActiveButton(this);
              };

              // ***************************************
              // activate the sketch to create a rectangle
              // ***************************************
              var drawRectangleButton = document.getElementById(
                "rectangleButton");
              drawRectangleButton.onclick = function() {
                reset();
                // set the sketch to create a polygon geometry
                sketchViewModel.create("rectangle");
                setActiveButton(this);
              };

              // ***************************************
              // activate the sketch to create a circle
              // ***************************************
              var drawCircleButton = document.getElementById("circleButton");
              drawCircleButton.onclick = function() {
                reset();
                // set the sketch to create a polygon geometry
                sketchViewModel.create("circle");
                setActiveButton(this);
              };

              // **************
              // reset button
              // **************
              document.getElementById("resetBtn").onclick = function() {
                reset();
              };

              function reset(){
                sketchViewModel.reset();
                tempGraphicsLayer.removeAll();
                setActiveButton();
              }

              function setActiveButton(selectedButton) {
                // focus the view to activate keyboard shortcuts for sketching
                view.focus();
                var elements = document.getElementsByClassName("active");
                for (var i = 0; i < elements.length; i++) {
                  elements[i].classList.remove("active");
                }
                if (selectedButton) {
                  selectedButton.classList.add("active");
                }
              }

              document.getElementById("secarch").onclick = function(){
                let url = "http://www.dzmap.cn/arcgis/rest/services/hn1w/MapServer/0";
                var queryTask =new QueryTask(url);
                var query =new Query();
                //query.returnGeometry=true;//返回空间查询到geometry，方便把返回值结果以图标形式叠加在地图上
                query.outFields =["现势性","平面坐标系","高程基准","是否整合","整合完成时","整合测区名","1万标准图"];//返回的字段名称
                query.outSpatialReference = map.spatialReference;

                let sqlwhere = '';
                if(_this.zhcqm!=''){
                  sqlwhere = "整合测区名 like '"+_this.zhcqm+"'";
                }
                if(sqlwhere!='' && _this.ywbzt!=""){
                  sqlwhere += " and ";
                }
                if(_this.ywbzt!=""){
                  sqlwhere += "\"1万标准图\" like '"+_this.ywbzt+"'";
                }

                if(sqlwhere!=''){
                  query.where = sqlwhere;
                }
                console.log(query.where);
                console.log(_this.tqfs);
                switch(_this.tqfs)
                {
                  case "相交":{
                    query.spatialRelationship = "intersects";
                  }break;
                  case "包含":{
                    query.spatialRelationship = "contains";
                  }
                }
                console.log(tempGraphicsLayer.graphics.length);
                if(tempGraphicsLayer.graphics.length>0){
                  query.geometry = tempGraphicsLayer.graphics.getItemAt(0).geometry;
                }
                queryTask.execute(query).then(showQueryResult);
              }

              function showQueryResult(featureSet) {
                console.log(featureSet);
                _this.alldata = featureSet.features;
                _this.totalCount = featureSet.features.length;
                _this.nowpagr = 1;
                _this.data = _this.alldata.slice(_this.pszie*(_this.nowpagr-1),_this.pszie);
                console.log("111");
              }

              // {
              //   tempGraphicsLayer.getGraphic(1)
              //   var meetsStandardSize = tempGraphicsLayer.graphics.every(function(item, i){
              //     item.geometry
              //     return calculateArea(item.geometry) > 1000;
              //   });
              // }

              document.getElementById("testbt").onclick = function(){
                  alert(tempGraphicsLayer.graphics.length);
                  var geometry = tempGraphicsLayer.graphics.getItemAt(0).geometry
                  var symbol;

                  // Choose a valid symbol based on return geometry
                  switch (geometry.type) {
                    case "point":
                      symbol = pointSymbol;
                      break;
                    case "polyline":
                      symbol = polylineSymbol;
                      break;
                    default:
                      symbol = polygonSymbol;
                      break;
                  }
                  // Create a new graphic; add it to the GraphicsLayer
                  var graphic = new Graphic({
                    geometry: geometry,
                    symbol: symbol
                  });
                  reset();
                  tempGraphicsLayer.add(graphic);
              }

              // function GomAddtoGrap(gom){
              //   var geometry = gom
              //     var symbol;

              //     // Choose a valid symbol based on return geometry
              //     switch (geometry.type) {
              //       case "point":
              //         symbol = pointSymbol;
              //         break;
              //       case "polyline":
              //         symbol = polylineSymbol;
              //         break;
              //       default:
              //         symbol = polygonSymbol;
              //         break;
              //     }
              //     // Create a new graphic; add it to the GraphicsLayer
              //     var graphic = new Graphic({
              //       geometry: geometry,
              //       symbol: symbol
              //     });
              //     tempGraphicsLayer.add(graphic);
              // }

              // ************************************************************************************
              // set up logic to handle geometry update and reflect the update on "tempGraphicsLayer"
              // ************************************************************************************
              function setUpClickHandler() {
                view.on("click", function(evt) {
                  view.hitTest(evt).then(function(response) {
                    var results = response.results;
                    // Found a valid graphic
                    if (results.length && results[results.length - 1]
                      .graphic) {
                      // Check if we're already editing a graphic
                      if (!updateGraphic) {
                        // Save a reference to the graphic we intend to update
                        updateGraphic = results[results.length - 1].graphic;
                        // Remove the graphic from the GraphicsLayer
                        // Sketch will handle displaying the graphic while being updated
                        tempGraphicsLayer.remove(updateGraphic);
                        sketchViewModel.update(updateGraphic.geometry);
                      }
                    }
                  });
                });
              }
                      
            });          
          }, reason => {
            console.log (reason);
          });
      }      
    }
  }
</script>

// http://www.dzmap.cn/arcgis/rest/services/vec/MapServer 矢量
// http://www.dzmap.cn/arcgis/rest/services/ant/MapServer 注记
// http://www.dzmap.cn/arcgis/rest/services/img_services/MapServer 影像
// http://www.dzmap.cn/arcgis/rest/services/imgzhuji/MapServer 影像注记
// http://www.dzmap.cn/arcgis/rest/services/hn1w/MapServer 1万网格


